<template>
  <basic-container>

    <el-collapse>
      <el-collapse-item name="1">
        <template #title>
          <el-text type="info">
            <el-icon>
              <Warning />
            </el-icon>
            提示：
          </el-text>
        </template>

        <div>
          <el-text type="info">
            1.导出时，先 ”搜索“，再 ”导出“。否则查询条件不会生效。
          </el-text>
        </div>

      </el-collapse-item>
    </el-collapse>


    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.customersituation_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.customersituation_edit"
                   @click="handleExport">导出
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/restaurant/customersituation";
  import {mapGetters} from "vuex";
  import {baseUrl} from "@/config/env";
  import {getAreaTree} from "@/api/restaurant/area";
  import { serialize } from '@/utils/util';
  import { getToken } from '@/utils/auth';

  export default {
    data() {
      return {
        form: {},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          labelWidth: 120,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: '填单日期',
              hide: true,
              prop: 'searchTime',
              type: 'date',
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              search: true,
              searchSpan: 8,
              searchRange: true,
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            {
              label: "归属区域",
              prop: "areaName",
              editDisabled: true,
              addDisabled: true,
              rules: [{
                required: false,
                message: "请输入归属区域",
                trigger: "blur"
              }]
            },
            {
              label: "房间",
              prop: "roomId",
              multiple: false,
              filterable: true,
              type: "tree",
              dicData: [],
              props: {
                label: "title"
              },
              slot: true,
              checkStrictly: true,
              rules: [{
                required: true,
                message: "房间",
                trigger: "click"
              }]
            },
            {
              label: "填单日期",
              prop: "writeDate",
              type: "date",
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              rules: [{
                required: true,
                message: "请输入填单日期",
                trigger: "blur"
              }]
            },
            {
              label: "类型",
              type: "select",
              prop: "timeSlot",
              dicData: [{
                label: '午市',
                value: '0'
              }, {
                label: '晚市',
                value: '1'
              }],
              search: true,
              rules: [{
                required: true,
                message: "请输入类型",
                trigger: "blur"
              }]
            },
            {
              label: "订房人",
              prop: "booker",
              type: "select",
              dicUrl: baseUrl + "/restaurant/common/userListByBooker",
              props: {
                label: "name",
                value: "name"
              },
              rules: [{
                required: true,
                message: "请输入订房人",
                trigger: "blur"
              }]
            },
            {
              label: "看台服务员",
              prop: "standAttendant",
              type: "select",
              dicUrl: baseUrl + "/restaurant/common/userListByStand",
              props: {
                label: "name",
                value: "name"
              },
              rules: [{
                required: true,
                message: "请输入看台服务员",
                trigger: "blur"
              }]
            },
            {
              label: "用餐人数",
              prop: "eatNum",
              rules: [{
                required: true,
                message: "请输入用餐人数",
                trigger: "blur"
              }]
            },
            {
              label: "贵宾姓名",
              prop: "guestName",
              rules: [{
                required: true,
                message: "请输入贵宾姓名",
                trigger: "blur"
              }]
            },
            {
              label: "客人类型",
              prop: "guestType",
              type: 'select',
              dicData: [{
                label: '优质',
                value: 0
              }, {
                label: '潜在',
                value: 1
              }, {
                label: '低频',
                value: 2
              }],
            },
             {
              label: "性别",
              prop: "sex",
              type: 'select',
              dicData: [{
                label: '男',
                value: 1
              }, {
                label: '女',
                value: 2
              }, {
                label: '未知',
                value: -1
              }],
            },
            {
              label: "电话",
              prop: "contact",
              search: true,
              rules: [{
                required: true,
                message: "请输入电话",
                trigger: "blur"
              }]
            },
            {
              label: "宴请性质",
              type: "select",
              dicUrl: baseUrl + "/blade-system/dict/dictionary?code=customer_entertain",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              slot: true,
              prop: "entertain",
              rules: [{
                required: true,
                message: "请输入宴请性质",
                trigger: "blur"
              }]
            },
            {
              label: "消费金额",
              prop: "amount",
              rules: [{
                required: true,
                message: "请输入消费金额",
                trigger: "blur"
              }]
            },
            {
              label: "结账方式",
              type: "select",
              dicUrl: baseUrl + "/blade-system/dict/dictionary?code=customer_payment_method",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              slot: true,
              prop: "paymentMethod",
              rules: [{
                required: true,
                message: "请输入结账方式",
                trigger: "blur"
              }]
            },

            {
              label: "禁忌、喜好",
              prop: "preference",
              type: "textarea",
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入禁忌、喜好",
                trigger: "blur"
              }]
            },
            {
              label: "意见",
              prop: "comments",
              type: "textarea",
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入意见",
                trigger: "blur"
              }]
            },
            {
              label: "菜品",
              prop: "items",
              type: "upload",
              listType: "picture-card",
              overHidden: true,
              width: "120",
              span: 24,
              action: "/api/blade-resource/oss/endpoint/put-file",
              propsHttp: {
                res: 'data',
                url: 'link'
              },
              rules: [{
                required: true,
                message: "请输入菜品",
                trigger: "blur"
              }],
            },
            {
              label: "提交人",
              prop: "createUserName"
            },
            {
              label: "修改人",
              prop: "updateUserName"
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.customersituation_add, false),
          viewBtn: this.validData(this.permission.customersituation_view, false),
          delBtn: this.validData(this.permission.customersituation_delete, false),
          editBtn: this.validData(this.permission.customersituation_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      async handleExport() {
        this.$confirm(`确定导出客情数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('导出查询条件：', serialize(this.query));
          window.open(`/api/restaurant/customersituation/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        row.roomName = this.findObject(this.option.column, "roomId").dicData.find(ele => ele.value === row.roomId).title;
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;

          getAreaTree(2).then(res => {
            const column = this.findObject(this.option.column, "roomId");
            column.dicData = res.data.data;
          });

          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
